package top.readhub.wopei.client.loader;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.readhub.wopei.common.api.ISettingApiService;
import top.readhub.wopei.common.exception.WoPeiException;
import top.readhub.wopei.common.utils.NumberUtil;

import java.util.List;

/**
 * Created by daervin on 2021/6/11
 */
public class ServiceLoader implements ILoader {
    private Logger logger = LoggerFactory.getLogger(ServiceLoader.class);

    private static ISettingApiService apiService;

    @Override
    public String getSetting(String keyword) throws WoPeiException {
        return init().get(keyword);
    }

    public List<String> getSettingAll(String keyword) throws WoPeiException {
        return init().gets(keyword);
    }

    private static ISettingApiService init() {
        if (apiService != null) {
            return apiService;
        }
        synchronized (ServiceLoader.class) {
            if (apiService != null) {
                return apiService;
            }
            ApplicationConfig application = new ApplicationConfig();
            application.setName("wpc_" + NumberUtil.getUUID());
            RegistryConfig registryConfig = new RegistryConfig();
            registryConfig.setProtocol("zookeeper");
            registryConfig.setAddress("zookeeper://127.0.0.1:2181");
            registryConfig.setCheck(false);
            application.setRegistry(registryConfig);
            application.setQosEnable(false);

            ReferenceConfig<ISettingApiService> reference = new ReferenceConfig<>();
//        reference.setGeneric(true);
            reference.setApplication(application);
            reference.setInterface(ISettingApiService.class);
            apiService = reference.get();
        }
        return apiService;
    }
}
